package com.basic.java.threads.lock;

/**
 * 造成死锁类
 * 创建时间：2022/4/20 20:03
 *
 * @author gejin
 */
public class DeadLock {
    public static void main(String[] args) {
        GirlMakeUp g1 = new GirlMakeUp(0, "西施");
        GirlMakeUp g2 = new GirlMakeUp(1, "凤姐");
        g1.start();
        g2.start();
    }
}

// 镜子
class Mirror {

}

// 口红
class LipStick {
}

// 女孩要化妆啦
class GirlMakeUp extends Thread {
    // 要获取的资源
    private static Mirror mirror = new Mirror();
    private static LipStick lipStick = new LipStick();

    private int count;
    private String girlName;

    public GirlMakeUp(int count, String girlName) {
        this.count = count;
        this.girlName = girlName;
    }

    @Override
    public void run() {
        // 化妆
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 化妆这个方法
    private void makeup() throws InterruptedException {
        if (count == 0) {
            synchronized (mirror) { // 拿到镜子的锁
                System.out.println(girlName + "拿到了镜子的锁！");
                Thread.sleep(1000);
            }
            synchronized (lipStick) {// 拿到口红的锁
                System.out.println(girlName + "拿到了口红的锁！");
            }
        } else {
            synchronized (lipStick) { // 拿到镜子的锁
                System.out.println(girlName + "拿到了口红的锁！");
                Thread.sleep(2000);
            }
            synchronized (mirror) {// 拿到口红的锁
                System.out.println(girlName + "拿到了镜子的锁！");
            }
        }
    }
}
